package com.xzst.jacksonxml.util;


import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @ClassName: FileUtil
 * @Author: LiuKeXin
 * @Date: Create in 2019-03-26 16:51
 */
@Slf4j
public class FileUtils {

    public static void writeFile(File file, String content) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        osw.write(content);
        osw.flush();
    }

    public static void appendFile(File file, String content) throws IOException {
        OutputStreamWriter out = new OutputStreamWriter(
                new FileOutputStream(file, true), // true to append
                "UTF-8"
        );

        out.write(content);
        out.close();
    }

    public static String readFile(File file) throws IOException {
        String content;
        StringBuilder sb = new StringBuilder();
        BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        while ((content = read.readLine()) != null) {
            sb.append(content + "\n");
        }
        read.close();
        return sb.toString();
    }

    /**
     * 创建文件夹
     *
     * @param destDirName
     */
    public static void createDir(String path) {
        File dir = new File(path);
        if (!dir.exists()) dir.mkdir();
    }

    /**
     * 创建文件
     *
     * @param path     文件目录
     * @param filename
     * @return
     * @throws IOException
     */
    public static void createFile(String path, String filename) throws IOException {
        File dir = new File(path);
        if (!dir.exists()) dir.mkdir();
        File file = new File(path + File.separator + filename);
        if (!file.exists()) {
            file.createNewFile();
        }
    }

    /**
     * 创建文件并写入内容
     *
     * @param path     文件目录
     * @param filename
     * @return
     * @throws IOException
     */
    public static Boolean createFile(String path, String filename, String content) {
        Boolean flag = false;
        try {
            File dir = new File(path);
            if (!dir.exists()) dir.mkdir();
            File file = new File(path + File.separator + filename);
            if (!file.exists()) {
                file.createNewFile();
                flag = true;
                writeFile(file, content);
            }
        } catch (IOException e) {
            log.error("IOException ===>" + e.getMessage());
            e.printStackTrace();
        }
        return flag;
    }

}
